﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using System;
using System.Text;

namespace Coldairarrow.Util.RabbitMQ
{
    public class RabbitMQClient: ISingletonDependency
    {

        private readonly IModel _channel;
        private readonly ILogger _logger;

        public RabbitMQClient(IConfiguration configuration, ILogger<RabbitMQClient> logger)
        {
            string userName = configuration.GetSection("Rabbitmq:UserName").Value;
            string password = configuration.GetSection("Rabbitmq:Password").Value;
            string hostName = configuration.GetSection("Rabbitmq:HostName").Value;
            int port = configuration.GetSection("Rabbitmq:Port").Value.ToInt();
            try
            {
                var factory = new ConnectionFactory()
                {
                    HostName = hostName,
                    UserName = userName,
                    Password = password,
                    Port = port,
                };
                var connection = factory.CreateConnection();
                _channel = connection.CreateModel();
            }
            catch (Exception ex)
            {
                logger.LogError(-1, ex, "RabbitMQClient init fail");
            }
            _logger = logger;
        }

        public virtual void PushMessage(string routingKey, object message)
        {
            _logger.LogInformation($"PushMessage,routingKey:{routingKey}");
            _channel.QueueDeclare(queue: routingKey,
                                        durable: false,
                                        exclusive: false,
                                        autoDelete: false,
                                        arguments: null);
            string msgJson = JsonConvert.SerializeObject(message);
            var body = Encoding.UTF8.GetBytes(msgJson);
            _channel.BasicPublish(exchange: "",
                                    routingKey: routingKey,
                                    basicProperties: null,
                                    body: body);
        }
    }
}
